# -*- coding: utf-8 -*-

from odoo import models, fields, api, _
from odoo.exceptions import ValidationError


class CpqBom(models.Model):
    """BOM版本主表"""
    _name = 'cpq.bom'
    _description = 'BOM版本'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _order = 'project_id, version_sequence desc, id desc'

    # 基本信息
    name = fields.Char(
        string='BOM名称',
        required=True,
        tracking=True,
        help='如: MS11项目前保总成BOM清单'
    )
    project_id = fields.Many2one(
        'cpq.project',
        string='项目',
        required=True,
        ondelete='cascade',
        tracking=True
    )
    
    # 版本信息
    version_type = fields.Selection([
        ('l1', 'L1 - 初版'),
        ('l2', 'L2 - 竞标锁定版'),
        ('l3', 'L3 - SOP版'),
        ('custom', '自定义版本')
    ], string='版本类型', default='l1', required=True, tracking=True)
    
    version_name = fields.Char(
        string='版本名称',
        tracking=True,
        help='如: V1.0、V2.0'
    )
    version_number = fields.Char(
        string='版本号',
        compute='_compute_version_number',
        store=True,
        help='版本号 (兼容字段)'
    )
    version_sequence = fields.Integer(
        string='版本序号',
        default=1,
        help='用于排序,数字越大越新'
    )
    
    # 状态
    state = fields.Selection([
        ('draft', '草稿'),
        ('confirmed', '已确认'),
        ('locked', '已锁定'),
    ], string='状态', default='draft', required=True, tracking=True)
    
    # 兼容字段 - 用于与 bmpt_cpq 模块兼容
    is_locked = fields.Boolean(
        string='是否锁定',
        compute='_compute_is_locked',
        store=True,
        help='兼容字段，根据state计算'
    )
    
    # BOM行数据
    line_ids = fields.One2many(
        'cpq.bom.line',
        'bom_id',
        string='BOM明细'
    )
    line_count = fields.Integer(
        string='BOM行数',
        compute='_compute_line_count'
    )
    
    # 对比相关
    compare_to_id = fields.Many2one(
        'cpq.bom',
        string='对比基准版本',
        help='与哪个版本进行对比'
    )
    has_changes = fields.Boolean(
        string='有变更',
        compute='_compute_has_changes',
        store=True
    )
    new_lines_count = fields.Integer(
        string='新增行数',
        compute='_compute_change_counts'
    )
    modified_lines_count = fields.Integer(
        string='修改行数',
        compute='_compute_change_counts'
    )
    deleted_lines_count = fields.Integer(
        string='删除行数',
        compute='_compute_change_counts'
    )
    
    # 导入信息
    import_file_name = fields.Char(
        string='导入文件名',
        help='Excel文件名'
    )
    import_date = fields.Datetime(
        string='导入时间',
        default=fields.Datetime.now
    )
    import_format = fields.Selection([
        ('benz', '奔驰格式(空格缩进)'),
        ('xiaomi', '小米格式(序号层级)'),
        ('unknown', '未知格式')
    ], string='BOM格式')
    
    # 备注
    description = fields.Text(string='版本说明')
    notes = fields.Html(string='备注')
    
    # 锁定信息
    locked_date = fields.Datetime(string='锁定时间', readonly=True)
    locked_by = fields.Many2one('res.users', string='锁定人', readonly=True)
    
    @api.depends('line_ids')
    def _compute_line_count(self):
        """计算BOM行数"""
        for bom in self:
            bom.line_count = len(bom.line_ids)
    
    @api.depends('version_name', 'version_sequence')
    def _compute_version_number(self):
        """计算版本号 - 兼容字段"""
        for bom in self:
            if bom.version_name:
                bom.version_number = bom.version_name
            else:
                bom.version_number = f'V{bom.version_sequence}'
    
    @api.depends('state')
    def _compute_is_locked(self):
        """计算是否锁定 - 兼容字段"""
        for bom in self:
            bom.is_locked = (bom.state == 'locked')
    
    @api.depends('line_ids.change_type')
    def _compute_has_changes(self):
        """检查是否有变更"""
        for bom in self:
            bom.has_changes = any(
                line.change_type in ('new', 'modified', 'deleted')
                for line in bom.line_ids
            )
    
    @api.depends('line_ids.change_type')
    def _compute_change_counts(self):
        """计算各类变更的数量"""
        for bom in self:
            bom.new_lines_count = len(bom.line_ids.filtered(lambda l: l.change_type == 'new'))
            bom.modified_lines_count = len(bom.line_ids.filtered(lambda l: l.change_type == 'modified'))
            bom.deleted_lines_count = len(bom.line_ids.filtered(lambda l: l.change_type == 'deleted'))
    
    def action_lock(self):
        """锁定BOM版本"""
        self.ensure_one()
        if self.state == 'locked':
            raise ValidationError(_('BOM已经被锁定'))
        
        self.write({
            'state': 'locked',
            'locked_date': fields.Datetime.now(),
            'locked_by': self.env.user.id
        })
        
        # 如果是L2版本，更新项目状态
        if self.version_type == 'l2':
            self.project_id.write({'state': 'l2'})
    
    def action_unlock(self):
        """解锁BOM版本"""
        self.ensure_one()
        if not self.env.user.has_group('cpq_qms.group_cpq_manager'):
            raise ValidationError(_('只有管理员可以解锁BOM'))
        
        self.write({
            'state': 'draft',
            'locked_date': False,
            'locked_by': False
        })
    
    def action_compare(self):
        """对比BOM版本"""
        self.ensure_one()
        return {
            'name': _('BOM版本对比'),
            'type': 'ir.actions.act_window',
            'res_model': 'cpq.bom.compare.wizard',
            'view_mode': 'form',
            'target': 'new',
            'context': {
                'default_new_bom_id': self.id,
                'default_old_bom_id': self.compare_to_id.id if self.compare_to_id else False
            }
        }
    
    def action_view_lines(self):
        """查看BOM明细（层级结构）"""
        self.ensure_one()
        return {
            'name': _('BOM明细'),
            'type': 'ir.actions.act_window',
            'res_model': 'cpq.bom.line',
            'view_mode': 'hierarchy,list,form',
            'domain': [('bom_id', '=', self.id), ('parent_id', '=', False)],
            'context': {
                'default_bom_id': self.id,
            }
        }
